package com.zc.common.mq.consumer;

import com.alibaba.fastjson.JSON;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * <p>Description : </p>
 *
 * @author : xuhongcao
 * @version : v1.0.0
 * @since : 6/4/2022
 **/
public class ReceiveMessageDaoImpl implements ReceiveMessageDao {

    private final JdbcTemplate jdbcTemplate;

    public ReceiveMessageDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void insert(String messageKey, String topic, String serializable) {
        String sql = "insert into receive_message_log(message_key, topic, body, created_at) values('%s', '%s', '%s', now())";
        String format = String.format("insert into receive_message_log(message_key, topic, body, created_at) values('%s', '%s', '%s', now())", messageKey, topic, serializable);
        this.jdbcTemplate.execute(format);
    }

    @Override
    public void insert(String messageKey, String topic, String tag, Object body) {
        String sql = "insert into `receive_message_log` (`message_key`, `topic`, `tag`, `body`) VALUES ('%s', '%s', '%s', '%s')";
        String format = String.format("insert into `receive_message_log` (`message_key`, `topic`, `tag`, `body`) VALUES ('%s', '%s', '%s', '%s')", messageKey, topic, tag, JSON.toJSONString(body));
        this.jdbcTemplate.execute(format);
    }

    @Override
    public Boolean existByMessageKey(String messageKey) {
        String sql = "select exists(select 1 from receive_message_log where message_key = '%s') ";
        String format = String.format("select exists(select 1 from receive_message_log where message_key = '%s') ", messageKey);
        return (Boolean)this.jdbcTemplate.queryForObject(format, Boolean.class);
    }
}
